﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Text.RegularExpressions;

namespace XCommunity.Web
{
  public class GuestAccount : Account
  {

    private string _username;

    private GuestAccount( string username )
    {
      _username = username;
    }


    private const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static readonly Random random = new Random( DateTime.Now.Millisecond );

    private static readonly Regex guestAccountTokenRegex = new Regex( "^_[0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{10}%$", RegexOptions.Compiled );

    private static string GenerateGuestUsername()
    {
      StringBuilder builder = new StringBuilder( "_" );

      for ( int i = 0; i < 10; i++ )
        builder.Append( chars[random.Next( chars.Length )] );

      return builder.ToString();
    }



    internal override string Token
    {
      get { return _username + "%"; }
    }


    /// <summary>
    /// 是否已通过身份验证（恒为false）
    /// </summary>
    public override bool IsAuthenticated
    {
      get { return false; }
    }

    /// <summary>
    /// 用户名（一个以下划线开头的随机字符串）
    /// </summary>
    public override string Name
    {
      get { return _username; }
    }


    /// <summary>
    /// 创建一个GuestAccount实例
    /// </summary>
    /// <returns></returns>
    public static Account Create()
    {
      var username = GenerateGuestUsername();
      return new GuestAccount( username );
    }

    /// <summary>
    /// 透过token创建GuestAccount实例
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public static Account Create( string token )
    {

      if ( !guestAccountTokenRegex.IsMatch( token ) )//如果是非法的token，则重新创建一个来宾账户
        return Create();

      var username = token.TrimEnd( '%' );
      return new GuestAccount( username );
    }
  }
}
